package edu.njust.httpmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.njust.httpmanager.entity.ProgramMember;
import edu.njust.httpmanager.entity.User;
import edu.njust.httpmanager.entity.dto.ProgramMemberDto;
import edu.njust.httpmanager.exception.CustomException;
import edu.njust.httpmanager.mapper.ProgramMemberMapper;
import edu.njust.httpmanager.mapper.UserMapper;
import edu.njust.httpmanager.service.IProgramMemberService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProgramMemberServiceImpl extends ServiceImpl<ProgramMemberMapper, ProgramMember> implements IProgramMemberService {

    @Resource
    private ProgramMemberMapper memberMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public ProgramMember getAuth(Long userId, Long programId) {

        LambdaQueryWrapper<ProgramMember> memberLambdaQueryWrapper = new LambdaQueryWrapper<>();

        memberLambdaQueryWrapper.eq(ProgramMember::getProgramId, programId)
                                .eq(ProgramMember::getUserId, userId);

        ProgramMember member = memberMapper.selectOne(memberLambdaQueryWrapper);

        return member;
    }

    @Override
    public List<ProgramMemberDto> getWithAuthAndNameByProgramId(Long programId) {
        // 返回结果
        List<ProgramMemberDto> memberDtos;

        LambdaQueryWrapper<ProgramMember> memberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        memberLambdaQueryWrapper.eq(ProgramMember::getProgramId, programId)
                .orderByAsc(ProgramMember::getUserRole);

        // 查询
        List<ProgramMember> programMembers = memberMapper.selectList(memberLambdaQueryWrapper);

        memberDtos = programMembers.stream().map((item) -> {
            ProgramMemberDto memberDto = new ProgramMemberDto();

            // 拷贝原有属性
            BeanUtils.copyProperties(item, memberDto);
            // 查询
            User user = userMapper.selectById(item.getUserId());
            String name = user.getName();
            memberDto.setName(name);

            return memberDto;
        }).collect(Collectors.toList());

        return memberDtos;
    }

    @Override
    public boolean joinIn(ProgramMember member) {
        // 检查是否已经加入项目
        LambdaQueryWrapper<ProgramMember> memberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        memberLambdaQueryWrapper.eq(ProgramMember::getUserId, member.getUserId())
                .eq(ProgramMember::getProgramId, member.getProgramId());

        if (memberMapper.selectOne(memberLambdaQueryWrapper) != null) {
            throw new CustomException("已经是项目成员，不可重复加入项目");
        }

        return memberMapper.insert(member) != 0;

    }

}
